// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UILiveObjectsRegistry.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.UI.Forms
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Runtime.Remoting;
    using System.Windows.Forms;

    using Org.OpenTrader.Framework.Events;
    using Org.OpenTrader.Framework.LiveObjects;
    using Org.OpenTrader.Framework.LiveObjects.Interfaces;

    #endregion

    /// <summary>
    /// The ui live objects registry.
    /// </summary>
    public partial class UILiveObjectsRegistry : UIControl
    {
        #region Constants and Fields

        /// <summary>
        /// The descriptors.
        /// </summary>
        private IDictionary<Guid, ILiveObjectContainerDescriptor> descriptors =
            new Dictionary<Guid, ILiveObjectContainerDescriptor>();

        /// <summary>
        /// The selectedContainer.
        /// </summary>
        private Guid selectedContainer;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="UILiveObjectsRegistry"/> class.
        /// </summary>
        public UILiveObjectsRegistry()
        {
            this.InitializeComponent();
        }

        #endregion

        #region Methods

        /// <summary>
        /// The containerGrid_ ui grid query cell info.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void OnContainerGridUIGridQueryCellInfo(object sender, VirtualGridEventArgs.QueryCellInfo e)
        {
            try
            {
                var container = Singleton<LiveObjectsRegistry>.Instance.GetContainer(this.selectedContainer);

                var rowCount = container.AllLiveObjects.Length;
                if (e.RowIndex >= rowCount || e.RowIndex < 0)
                {
                    return;
                }

                var objectId = container.AllLiveObjects[e.RowIndex];

                var obj = container.GetLiveObject<ILiveObject>(objectId);
                var desc = obj.Descriptor;

                switch (e.ColumnIndex)
                {
                    case 0:
                        e.Value = desc.ID;
                        break;

                    case 1:
                        if (desc.Label != null)
                        {
                            e.Value = desc.Name + " (" + desc.Label + ")";
                        }
                        else
                        {
                            e.Value = desc.Name;
                        }

                        break;

                    case 2:
                        e.Value = desc.InterfaceType;
                        break;
                }
            }
            catch (RemotingException)
            {
                e.Value = "Remoting Exception";
            }
        }

        /// <summary>
        /// The containerGrid_ ui grid query row count.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void OnContainerGridUIGridQueryRowCount(object sender, VirtualGridEventArgs.QueryRowCount e)
        {
            if (this.selectedContainer == Guid.Empty)
            {
                e.RowCount = 0;
            }
            else
            {
                var container = Singleton<LiveObjectsRegistry>.Instance.GetContainer(this.selectedContainer);
                e.RowCount = container.AllLiveObjects.Length;
            }
        }

        /// <summary>
        /// The containersGrid_ cell click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void OnContainersGridCellClick(object sender, DataGridViewCellEventArgs e)
        {
            var rowCount = Singleton<LiveObjectsRegistry>.Instance.Containers.Length;
            if (e.RowIndex >= rowCount || e.RowIndex < 0)
            {
                return;
            }

            this.selectedContainer = Singleton<LiveObjectsRegistry>.Instance.Containers[e.RowIndex];
            this.containerGrid.Refresh();
        }

        /// <summary>
        /// The containersGrid_ cell content click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void OnContainersGridCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        /// <summary>
        /// The ui virtual grid 1_ ui grid query cell info.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void OnVirtualGrid1UIGridQueryCellInfo(object sender, VirtualGridEventArgs.QueryCellInfo e)
        {
            var rowCount = Singleton<LiveObjectsRegistry>.Instance.Containers.Length;
            if (e.RowIndex >= rowCount || e.RowIndex < 0)
            {
                return;
            }

            var containerId = Singleton<LiveObjectsRegistry>.Instance.Containers[e.RowIndex];
            var container = Singleton<LiveObjectsRegistry>.Instance.GetContainer(containerId);
            ILiveObjectContainerDescriptor desc = null;
            string workingDir = null;
            string workingDirTooltip = null;
            string statusTooltip = null;
            string status;
            try
            {
                this.descriptors[containerId] = container.Descriptor;
                status = "Available";
            }
            catch (Exception ex)
            {
                status = "Unavailable";
                statusTooltip = ex.ToString();
            }

            if (this.descriptors.ContainsKey(containerId))
            {
                desc = this.descriptors[containerId];
                workingDir =
                    PathUtil.Cleanup(desc.WorkingDirectory.Replace(System.IO.Path.GetTempPath(), "...")).Substring(1);
                workingDirTooltip = PathUtil.Cleanup(desc.WorkingDirectory).Substring(1);
            }

            // According the column display required data
            switch (e.ColumnIndex)
            {
                case 0:

                    e.Value = (desc != null) ? desc.ID.ToString() : "?";
                    break;

                case 1:
                    e.Value = (desc != null) ? desc.Name : "?";
                    break;

                case 2:
                    e.Value = (desc != null) ? desc.Type.ToString() : "?";
                    break;

                case 3:
                    e.Value = workingDir;
                    e.ToolTip = workingDirTooltip;
                    break;

                case 4:
                    e.Value = status;
                    e.ToolTip = statusTooltip;

                    // if (available)
                    // virtualGrid[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.LightGreen;
                    // else
                    // virtualGrid[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Orange;
                    e.Value = status;
                    break;
            }
        }

        /// <summary>
        /// The ui virtual grid 1_ ui grid query row count.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void OnVirtualGrid1UIGridQueryRowCount(object sender, VirtualGridEventArgs.QueryRowCount e)
        {
            e.RowCount = Singleton<LiveObjectsRegistry>.Instance.Containers.Length;
        }

        #endregion
    }
}